package com.example.android.services

import android.content.Context
import android.util.Log
import com.example.android.R
import com.example.android.extensions.Services
import com.example.android.extensions.StringBody
import com.example.android.utils.Api
import com.example.android.utils.JsonUtil
import com.example.android.utils.models.Form
import com.example.android.utils.models.MyResult
import com.example.android.utils.websocket.MyWebSocket

/**
 * @ClassName SidebarService
 * @Author Ryan Kamanri
 * @Date 2022/6/1
 * @Description
 **/
class SidebarService(
    private val _WebSocket: MyWebSocket,
    private val _Api: Api,
    private val _JsonUtil: JsonUtil,
    private val _HashMapStorage: HashMap<String, String>,
    private val _SharedService: SharedService
) {
    /**
     * 获取菜单列表
     * return: 菜单列表(以resource id 形式)
     */
    suspend fun GetMenuList(): MyResult<ArrayList<Int>> {
        val token = _HashMapStorage["token"] ?: return MyResult()
        val menuMap = hashMapOf(
            1 to R.id.nav_self_info,
            2 to R.id.nav_select_bed,
            3 to R.id.nav_online_payment,
//            4 to R.id.nav_announce,
            22 to R.id.nav_announce,
            23 to R.id.nav_online_chat
        )

        val response = _Api.Get("/user/getMenuList") {
            it.addHeader("jwtToken", token)
        }

        val result = _JsonUtil.FromJsonObject(response.StringBody()).AsMyResult<ArrayList<Form>>()
        when (result.Code) {
            MyResult.OK -> {
                val resMenuIdList = arrayListOf<Int>()
                result.Data?.forEach {
                    val resMenuId = menuMap[it["permissionId"]]
                    if (resMenuId != null) {
                        resMenuIdList.add(resMenuId)
                    }
                }
                return MyResult(result.Code, result.Message, resMenuIdList)
            }
            else -> return MyResult()
        }
    }

    suspend fun Logout() {
        _HashMapStorage.remove("token")
        _WebSocket.Close()
        val cookieList = arrayListOf<String>()
        _Api.Get("/user/logout").headers.forEach {
            Log.d(toString(), "${it.first}: ${it.second}")
            if(it.first == "Set-Cookie") {
                cookieList.add(it.second)
            }
        }
        _SharedService.SetLocalCookies(cookieList)
    }
}

